package com.ruoyi.business.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Time;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.business.domain.Train;
import com.ruoyi.business.domain.dto.TrainCarriageGroupDTO;
import com.ruoyi.business.domain.vo.TrainStationVo;
import com.ruoyi.business.service.impl.TrainServiceImpl;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.TrainStation;
import com.ruoyi.business.service.ITrainStationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * 火车车站Controller
 * 
 * @author ruoyi
 * @date 2025-03-06
 */
@RestController
@RequestMapping("/base/train-station")
public class TrainStationController extends BaseController
{
    @Autowired
    private ITrainStationService trainStationService;

    @Autowired
    private TrainServiceImpl trainService;

    /**
     * 查询火车车站列表
     */
//    @PreAuthorize("@ss.hasPermi('base:train-station:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(TrainStation trainStation)
//    {
//        startPage();
//        List<TrainStation> list = trainStationService.selectTrainStationList(trainStation);
//        return getDataTable(list);
//    }

    /**
     * 导出火车车站列表
     */
    @PreAuthorize("@ss.hasPermi('base:train-station:export')")
    @Log(title = "火车车站", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TrainStation trainStation)
    {
        List<TrainStation> list = trainStationService.selectTrainStationList(trainStation);
        System.out.println(list.size());
        for (TrainStation station : list) {
            System.out.println(station+"!@#!@#!@#!@#!@#!@#!@#!@#");
        }
        ExcelUtil<TrainStation> util = new ExcelUtil<TrainStation>(TrainStation.class);
        util.exportExcel(response, list, "火车车站数据");
    }
//    /**
//     * 导入火车车站列表
//     */
//    @PreAuthorize("@ss.hasPermi('base:train-station:add')")
//    @Log(title = "火车车站", businessType = BusinessType.IMPORT)
//    @PostMapping("/importExcel")
//    public AjaxResult importExcel(MultipartFile file) throws IOException {
//        ExcelUtil<TrainStationVo> util = new ExcelUtil<TrainStationVo>(TrainStationVo.class);
//        List<TrainStationVo> list = util.importExcel(file.getInputStream());
//        List<TrainStation> trainStationList = new ArrayList<>();
//        for (TrainStationVo trainStationVo : list) {
//            TrainStation trainStation=new TrainStation();
//            trainStation.setId(IdUtil.getSnowflakeNextId());
//            trainStation.setTrainCode(trainStationVo.getTrainCode());
//            trainStation.setIndex(trainStationVo.getIndex());
//            trainStation.setName(trainStationVo.getName());
//            trainStation.setNamePinyin(trainStationVo.getNamePinyin());
//            trainStation.setInTime(Time.valueOf(trainStationVo.getInTime()));
//            trainStation.setOutTime(Time.valueOf(trainStationVo.getOutTime()));
//            trainStation.setStopTime(Time.valueOf(trainStationVo.getStopTime()));
//            trainStation.setKm(new BigDecimal(trainStationVo.getKm()));
//            trainStationList.add(trainStation);
//        }
//        return toAjax(trainStationService.InsertTrainStations(trainStationList));
//    }

    /**
     * 导入火车车站数据
     */
    @PreAuthorize("@ss.hasPermi('base:train-station:add')")
    @Log(title = "火车车站", businessType = BusinessType.IMPORT)
    @PostMapping("/importExcel")
    public AjaxResult importExcel(MultipartFile file) throws Exception {
        ExcelUtil<TrainStationVo> util = new ExcelUtil<>(TrainStationVo.class);
        List<TrainStationVo> vos = util.importExcel(file.getInputStream());
        
        // 用于收集错误数据
        List<TrainStationVo> errorList = new ArrayList<>();
        // 用于收集有效数据
        List<TrainStation> validStations = new ArrayList<>();
        
        // 用于检查一个车次下是否有重复的站序或站名
        Map<String, Set<Long>> trainCodeToIndices = new HashMap<>();
        Map<String, Set<String>> trainCodeToNames = new HashMap<>();
        
        // 用于记录每个车次的站点，以便后续确定终点站
        Map<String, List<TrainStationVo>> trainCodeToStations = new HashMap<>();
        
        int rowNum = 2; // Excel从第2行开始（第1行是表头）
        for (TrainStationVo vo : vos) {
            boolean isValid = true;
            StringBuilder errorMsg = new StringBuilder();
            
            // 1. 基础数据验证
            if (StringUtils.isEmpty(vo.getTrainCode())) {
                appendError(errorMsg, "车次编号不能为空");
                isValid = false;
            }
            
            // 特别判断站序是否真的存在，null、空字符串和未定义的情况
            if (vo.getIndex() == null || (vo.getIndex().toString().trim().isEmpty())) {
                appendError(errorMsg, "站序不能为空");
                isValid = false;
                // 显式标记站序为null，确保前端能正确识别
                vo.setIndex(null);
            } else {
                // 记录检测到的站序值，便于调试
                logger.info("Excel中的站序值: " + vo.getIndex() + ", 类型: " + vo.getIndex().getClass().getName());
            }
            
            if (StringUtils.isEmpty(vo.getName())) {
                appendError(errorMsg, "站名不能为空");
                isValid = false;
            }
            
            if (StringUtils.isEmpty(vo.getInTime())) {
                appendError(errorMsg, "进站时间不能为空");
                isValid = false;
            }
            
            if (StringUtils.isEmpty(vo.getOutTime())) {
                appendError(errorMsg, "出站时间不能为空");
                isValid = false;
            }
            
            if (StringUtils.isEmpty(vo.getKm()) && vo.getIndex() != null && vo.getIndex() != 0) {
                appendError(errorMsg, "里程不能为空");
                isValid = false;
            }
            
            // 如果基础验证未通过，继续下一条记录
            if (!isValid) {
                vo.setRowNum(rowNum);
                vo.setErrorMsg(errorMsg.toString());
                errorList.add(vo);
                rowNum++;
                continue;
            }
            
            // 2. 检查车次是否存在于列车管理中
            if (isValid && !StringUtils.isEmpty(vo.getTrainCode())) {
                // 通过trainService查询车次
                Train query = new Train();
                query.setCode(vo.getTrainCode());
                List<Train> existingTrains = trainService.selectTrainList(query);
                
                if (existingTrains == null || existingTrains.isEmpty()) {
                    appendError(errorMsg, "车次编号[" + vo.getTrainCode() + "]不存在于列车管理中");
                    isValid = false;
                }
            }
            
            // 3. 检查同一车次下的站序是否重复
            if (isValid && vo.getTrainCode() != null && vo.getIndex() != null) {
                Set<Long> indices = trainCodeToIndices.computeIfAbsent(vo.getTrainCode(), k -> new HashSet<>());
                //将indices遍历输出
                StringBuilder logMsg = new StringBuilder("当前已存在的站序: [");
                for (Long existingIndex : indices) {
                    logMsg.append(existingIndex).append(", ");
                }
                logMsg.append("]");
                logger.info(logMsg.toString());
                
                if (indices.contains(vo.getIndex())) {
                    appendError(errorMsg, "同一车次下站序[" + vo.getIndex() + "]重复");
                    isValid = false;
                } else {
                    indices.add(vo.getIndex());
                    logger.info("添加新站序: " + vo.getIndex() + " 到车次: " + vo.getTrainCode());
                }
            }
            
            // 4. 检查同一车次下的站名是否重复
            if (isValid && vo.getTrainCode() != null && vo.getName() != null) {
                Set<String> names = trainCodeToNames.computeIfAbsent(vo.getTrainCode(), k -> new HashSet<>());
                if (names.contains(vo.getName())) {
                    appendError(errorMsg, "同一车次下站名[" + vo.getName() + "]重复");
                    isValid = false;
                } else {
                    names.add(vo.getName());
                }
            }
            
            // 5. 检查进站时间和出站时间
            if (isValid && vo.getInTime() != null && vo.getOutTime() != null) {
                try {
                    Time inTime = Time.valueOf(vo.getInTime());
                    Time outTime = Time.valueOf(vo.getOutTime());


                    System.out.println(!outTime.equals(Time.valueOf("00:00:00"))+"!!!!!!!!!!!!!!!!!!!!");
                    System.out.println(outTime);
                    if (outTime.before(inTime) && !outTime.equals(Time.valueOf("00:00:00"))) {
                        appendError(errorMsg, "出站时间[" + vo.getOutTime() + "]不能早于进站时间[" + vo.getInTime() + "]");
                        isValid = false;
                    }
                } catch (Exception e) {
                    // 时间格式错误
                    if (vo.getId() == null) {
                        vo.setId(IdUtil.getSnowflakeNextId());
                    }
                    vo.setRowNum(rowNum);
                    appendError(errorMsg, "时间格式不正确: " + e.getMessage());
                    vo.setErrorMsg(errorMsg.toString());
                    errorList.add(vo);
                    rowNum++;
                    continue;
                }
            }
            
            // 6. 检查起始站的里程是否为0
            if (isValid && vo.getIndex() != null && vo.getIndex() == 0) {
                // 数值验证：转换为BigDecimal进行比较，解决0.00不被识别为0的问题
                if (vo.getKm() == null) {
                appendError(errorMsg, "第一站（站序为0）的里程必须为0");
                isValid = false;
                } else {
                    try {
                        BigDecimal km = new BigDecimal(vo.getKm());
                        // 使用compareTo检查是否等于0，避免浮点精度问题
                        if (km.compareTo(BigDecimal.ZERO) != 0) {
                            appendError(errorMsg, "第一站（站序为0）的里程必须为0，当前值为" + vo.getKm());
                            isValid = false;
                        }
                    } catch (NumberFormatException e) {
                        appendError(errorMsg, "里程格式不正确: " + e.getMessage());
                        isValid = false;
                    }
                }
            }
            
            // 如果数据有效，添加到该车次的站点集合中，用于后续确定终点站
            if (isValid) {
                List<TrainStationVo> stations = trainCodeToStations.computeIfAbsent(vo.getTrainCode(), k -> new ArrayList<>());
                stations.add(vo);
            } else {
                // 创建错误数据对象
                if (vo.getId() == null) {
                    vo.setId(IdUtil.getSnowflakeNextId());
                }
                vo.setRowNum(rowNum);
                vo.setErrorMsg(errorMsg.toString());
                errorList.add(vo);
            }
            
            rowNum++;
        }
        
        // 处理终点站：为每个车次找出站序最大的站点，将其出站时间和停站时间设为00:00:00
        for (Map.Entry<String, List<TrainStationVo>> entry : trainCodeToStations.entrySet()) {
            String trainCode = entry.getKey();
            List<TrainStationVo> stations = entry.getValue();
            
            if (!stations.isEmpty()) {
                // 按站序排序
                stations.sort(Comparator.comparing(TrainStationVo::getIndex));
                
                // 获取最大站序的站点（终点站）
                TrainStationVo lastStation = stations.get(stations.size() - 1);
                logger.info("车次[" + trainCode + "]的终点站为: " + lastStation.getName() + ", 站序: " + lastStation.getIndex());
                
                // 将终点站的出站时间设为00:00:00，注意不要改变进站时间
                lastStation.setOutTime("00:00:00");
                logger.info("终点站时间设置 - 车次: " + trainCode + ", 站名: " + lastStation.getName() + 
                           ", 站序: " + lastStation.getIndex() + 
                           ", 进站时间保持: " + lastStation.getInTime() + 
                           ", 出站时间设为: 00:00:00");
                // 停站时间会在后续的TrainStation对象创建时被自动计算
            }
        }
        
        // 将有效的数据转换为TrainStation对象
        for (Map.Entry<String, List<TrainStationVo>> entry : trainCodeToStations.entrySet()) {
            for (TrainStationVo vo : entry.getValue()) {
                TrainStation station = new TrainStation();
                // 确保ID有效，如果vo中没有ID，则生成新ID
                if (vo.getId() == null) {
                    station.setId(IdUtil.getSnowflakeNextId());
                    logger.info("为新记录生成ID: " + station.getId());
                } else {
                    station.setId(vo.getId());
                    logger.info("使用Excel中的ID: " + station.getId());
                }
                station.setTrainCode(vo.getTrainCode());
                station.setIndex(vo.getIndex());
                station.setName(vo.getName());
                station.setNamePinyin(vo.getNamePinyin());
                try {
                    // 直接使用valueOf方法将字符串转换为Time对象，保留原始格式
                    Time inTime = Time.valueOf(vo.getInTime());
                    Time outTime = Time.valueOf(vo.getOutTime());
                    
                    station.setInTime(inTime);
                    station.setOutTime(outTime);
                    
                    // 记录转换前后的时间，用于调试
                    logger.info("时间格式转换 - 车次: " + vo.getTrainCode() + 
                              ", 站名: " + vo.getName() + 
                              ", 原始进站时间: " + vo.getInTime() + 
                              ", 转换后进站时间: " + inTime + 
                              ", 原始出站时间: " + vo.getOutTime() + 
                              ", 转换后出站时间: " + outTime);
                    
                    // 对于终点站，直接设置停站时间为00:00:00
                    if ("00:00:00".equals(vo.getOutTime())) {
                        station.setStopTime(Time.valueOf("00:00:00"));
                        logger.info("终点站设置 - 车次: " + vo.getTrainCode() + ", 站名: " + vo.getName() + 
                                  ", 站序: " + vo.getIndex() + ", 出站时间和停站时间已设为00:00:00");
                    } else {
                        // 计算停站时长
                        long inTimeMs = inTime.getTime();
                        long outTimeMs = outTime.getTime();
                        long diffMs = outTimeMs - inTimeMs;
                        
                        if (diffMs < 0) {
                            // 如果是跨天，需要加上24小时
                            diffMs += 24 * 60 * 60 * 1000;
                        }
                        
                        // 正确计算停站时长，转换为HH:mm:ss格式
                        int hours = (int) (diffMs / (60 * 60 * 1000));
                        int minutes = (int) ((diffMs % (60 * 60 * 1000)) / (60 * 1000));
                        int seconds = (int) ((diffMs % (60 * 1000)) / 1000);
                        
                        // 确保时间在24小时内
                        hours = hours % 24;
                        
                        // 格式化为HH:mm:ss，使用24小时制
                        String stopTimeStr = String.format("%02d:%02d:%02d", hours, minutes, seconds);
                        Time stopTime = Time.valueOf(stopTimeStr);
                        
                        logger.info("停站时长计算 - 车次: " + vo.getTrainCode() + ", 站序: " + vo.getIndex() + 
                                   ", 进站: " + vo.getInTime() + ", 出站: " + vo.getOutTime() + 
                                   ", 时间差(ms): " + diffMs + ", 停站时长: " + stopTimeStr);
                        
                        station.setStopTime(stopTime);
                    }
                } catch (Exception e) {
                    // 时间格式错误
                    if (vo.getId() == null) {
                        vo.setId(IdUtil.getSnowflakeNextId());
                    }
                    vo.setRowNum(rowNum);
                    StringBuilder errorMsg = new StringBuilder();
                    appendError(errorMsg, "时间格式不正确: " + e.getMessage());
                    vo.setErrorMsg(errorMsg.toString());
                    errorList.add(vo);
                    continue;
                }
                
                try {
                    if (vo.getKm() != null) {
                        station.setKm(new BigDecimal(vo.getKm()));
                    }
                } catch (NumberFormatException e) {
                    // 里程格式错误
                    if (vo.getId() == null) {
                        vo.setId(IdUtil.getSnowflakeNextId());
                    }
                    vo.setRowNum(rowNum);
                    StringBuilder errorMsg = new StringBuilder();
                    appendError(errorMsg, "里程格式不正确: " + e.getMessage());
                    vo.setErrorMsg(errorMsg.toString());
                    errorList.add(vo);
                    continue;
                }
                
                validStations.add(station);
            }
        }
        
        // 检查已存在的数据，避免与数据库中的记录冲突
        List<TrainStation> stationsToKeep = new ArrayList<>();
        for (TrainStation station : validStations) {
            boolean shouldKeep = true;
            
            TrainStation query = new TrainStation();
            query.setTrainCode(station.getTrainCode());
            query.setIndex(station.getIndex());
            List<TrainStation> existingStations = trainStationService.selectTrainStationList(query);
            
            if (existingStations != null && !existingStations.isEmpty()) {
                // 判断是否真的是重复，还是ID不同的新记录
                boolean isDuplicate = false;
                for (TrainStation existingStation : existingStations) {
                    // 记录比较的信息，便于调试
                    logger.info("比较是否冲突 - 导入车次: " + station.getTrainCode() + ", 导入站序: " + station.getIndex() + 
                               ", 已存在车次: " + existingStation.getTrainCode() + ", 已存在站序: " + existingStation.getIndex());
                    
                    // 只有在车次编号和站序都相同的情况下，才认为是重复
                    if (existingStation.getTrainCode().equals(station.getTrainCode()) &&
                        existingStation.getIndex().equals(station.getIndex())) {
                        isDuplicate = true;
                        logger.info("检测到数据冲突: 车次[" + station.getTrainCode() + "] 站序[" + station.getIndex() + "]");
                        break;
                    }
                }
                
                if (isDuplicate) {
                // 记录已存在，标记为错误
                TrainStationVo errorVo = new TrainStationVo();
                errorVo.setId(station.getId());
                errorVo.setTrainCode(station.getTrainCode());
                errorVo.setIndex(station.getIndex());
                errorVo.setName(station.getName());
                errorVo.setNamePinyin(station.getNamePinyin());
                errorVo.setInTime(station.getInTime().toString());
                errorVo.setOutTime(station.getOutTime().toString());
                errorVo.setStopTime(station.getStopTime().toString());
                errorVo.setKm(station.getKm() != null ? station.getKm().toString() : null);
                errorVo.setRowNum(0); // 使用0表示系统检测的错误
                errorVo.setErrorMsg("该车次[" + station.getTrainCode() + "]下已存在站序[" + station.getIndex() + "]的记录");
                errorList.add(errorVo);
                
                    // 标记为不保留
                    shouldKeep = false;
                }
            }
            
            if (shouldKeep) {
            query = new TrainStation();
            query.setTrainCode(station.getTrainCode());
            query.setName(station.getName());
            existingStations = trainStationService.selectTrainStationList(query);
            
            if (existingStations != null && !existingStations.isEmpty()) {
                    // 判断是否真的是名称重复，还是ID不同的新记录
                    boolean isDuplicate = false;
                    for (TrainStation existingStation : existingStations) {
                        // 记录比较的信息，便于调试
                        logger.info("比较是否名称冲突 - 导入车次: " + station.getTrainCode() + ", 导入站名: " + station.getName() + 
                                   ", 已存在车次: " + existingStation.getTrainCode() + ", 已存在站名: " + existingStation.getName());
                        
                        // 只有在车次编号和站名都相同的情况下，才认为是重复
                        if (existingStation.getTrainCode().equals(station.getTrainCode()) &&
                            existingStation.getName().equals(station.getName())) {
                            isDuplicate = true;
                            logger.info("检测到数据冲突: 车次[" + station.getTrainCode() + "] 站名[" + station.getName() + "]");
                            break;
                        }
                    }
                    
                    if (isDuplicate) {
                // 记录已存在，标记为错误
                TrainStationVo errorVo = new TrainStationVo();
                errorVo.setId(station.getId());
                errorVo.setTrainCode(station.getTrainCode());
                errorVo.setIndex(station.getIndex());
                errorVo.setName(station.getName());
                errorVo.setNamePinyin(station.getNamePinyin());
                errorVo.setInTime(station.getInTime().toString());
                errorVo.setOutTime(station.getOutTime().toString());
                errorVo.setStopTime(station.getStopTime().toString());
                errorVo.setKm(station.getKm() != null ? station.getKm().toString() : null);
                errorVo.setRowNum(0); // 使用0表示系统检测的错误
                errorVo.setErrorMsg("该车次[" + station.getTrainCode() + "]下已存在站名[" + station.getName() + "]的记录");
                errorList.add(errorVo);
                
                        // 标记为不保留
                        shouldKeep = false;
                    }
                }
            }
            
            // 只保留通过所有验证的记录
            if (shouldKeep) {
                stationsToKeep.add(station);
            }
        }
        
        // 使用过滤后的列表替换原列表
        validStations = stationsToKeep;
        
        // 批量插入有效数据
        int successCount = 0;
        for (TrainStation station : validStations) {
            try {
                logger.info("开始导入数据 - 车次: " + station.getTrainCode() + ", 站序: " + station.getIndex() + ", ID: " + station.getId());
                int result = trainStationService.insertTrainStation(station);
                if (result > 0) {
                    successCount++;
                    logger.info("成功导入数据 - 车次: " + station.getTrainCode() + ", 站序: " + station.getIndex() + ", ID: " + station.getId());
                } else {
                    logger.warn("导入数据失败 - 车次: " + station.getTrainCode() + ", 站序: " + station.getIndex() + ", ID: " + station.getId() + ", 返回值: " + result);
                }
            } catch (Exception e) {
                // 记录插入失败的数据
                TrainStationVo errorVo = new TrainStationVo();
                errorVo.setId(station.getId());  // 使用有效数据的ID
                errorVo.setTrainCode(station.getTrainCode());
                errorVo.setIndex(station.getIndex());
                errorVo.setName(station.getName());
                errorVo.setNamePinyin(station.getNamePinyin());
                errorVo.setInTime(station.getInTime().toString());
                errorVo.setOutTime(station.getOutTime().toString());
                errorVo.setStopTime(station.getStopTime().toString());
                errorVo.setKm(station.getKm() != null ? station.getKm().toString() : null);
                errorVo.setRowNum(0); // 系统错误
                errorVo.setErrorMsg("数据库插入失败: " + e.getMessage());
                errorList.add(errorVo);
                
                // 记录详细错误日志
                logger.error("插入火车车站数据失败: 车次: " + station.getTrainCode() + ", 站序: " + station.getIndex() + ", ID: " + station.getId() + ", 错误: " + e.getMessage(), e);
            }
        }
        
        // 返回结果，包含完整的错误数据
        if (!errorList.isEmpty()) {
            AjaxResult result = AjaxResult.error("部分数据导入失败", errorList);
            result.put("successCount", successCount);
            return result;
        } else {
            return AjaxResult.success("成功导入" + successCount + "条数据");
        }
    }
    
    // 辅助方法：添加错误信息
    private void appendError(StringBuilder sb, String error) {
        if (sb.length() > 0) {
            sb.append("; ");
        }
        sb.append(error);
    }

    /**
     * 下载车站导入模板
     */
    @PreAuthorize("@ss.hasPermi('base:platform:export')")
    @Log(title = "火车车站", businessType = BusinessType.EXPORT)
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 使用自定义模板下载方法，不包含错误原因列和行号列
        trainStationService.downloadCustomTemplate(response);
    }


    /**
     * 获取火车车站详细信息
     */
    @PreAuthorize("@ss.hasPermi('base:train-station:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(trainStationService.selectTrainStationById(id));
    }

    private Time calculateStopTime(Time inTime, Time outTime) {
        // 如果出站时间是00:00:00，说明是终点站，直接返回00:00:00
        if (outTime.toString().equals("00:00:00")) {
            return Time.valueOf("00:00:00");
        }
        
        long inTimeMs = inTime.getTime();
        long outTimeMs = outTime.getTime();
        long diffMs = outTimeMs - inTimeMs;
        
        if (diffMs < 0) {
            // 如果是跨天，需要加上24小时
            diffMs += 24 * 60 * 60 * 1000;
        }
        
        // 计算时分秒
        int hours = (int) (diffMs / (60 * 60 * 1000));
        int minutes = (int) ((diffMs % (60 * 60 * 1000)) / (60 * 1000));
        int seconds = (int) ((diffMs % (60 * 1000)) / 1000);
        
        // 确保时间在24小时内
        hours = hours % 24;
        
        // 格式化为HH:mm:ss
        String stopTimeStr = String.format("%02d:%02d:%02d", hours, minutes, seconds);
        return Time.valueOf(stopTimeStr);
    }

    /**
     * 新增火车车站
     */
    @PreAuthorize("@ss.hasPermi('base:train-station:add')")
    @Log(title = "火车车站", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TrainStation trainStation)
    {
        trainStation.setId(IdUtil.getSnowflakeNextId());
        
        // 计算停站时长
        if (trainStation.getInTime() != null && trainStation.getOutTime() != null) {
            Time stopTime = calculateStopTime(trainStation.getInTime(), trainStation.getOutTime());
            trainStation.setStopTime(stopTime);
            
            logger.info("新增车站 - 停站时长计算 - 车次: " + trainStation.getTrainCode() + 
                        ", 站序: " + trainStation.getIndex() + 
                        ", 进站: " + trainStation.getInTime() + 
                        ", 出站: " + trainStation.getOutTime() + 
                        ", 停站时长: " + stopTime);
        }
        
        return toAjax(trainStationService.insertTrainStation(trainStation));
    }

    /**
     * 修改火车车站
     */
    @PreAuthorize("@ss.hasPermi('base:train-station:edit')")
    @Log(title = "火车车站", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TrainStation trainStation)
    {
        // 计算停站时长
        if (trainStation.getInTime() != null && trainStation.getOutTime() != null) {
            Time stopTime = calculateStopTime(trainStation.getInTime(), trainStation.getOutTime());
            trainStation.setStopTime(stopTime);
            
            logger.info("修改车站 - 停站时长计算 - 车次: " + trainStation.getTrainCode() + 
                        ", 站序: " + trainStation.getIndex() + 
                        ", 进站: " + trainStation.getInTime() + 
                        ", 出站: " + trainStation.getOutTime() + 
                        ", 停站时长: " + stopTime);
        }
        
        return toAjax(trainStationService.updateTrainStation(trainStation));
    }

    /**
     * 删除火车车站
     */
    @PreAuthorize("@ss.hasPermi('base:train-station:remove')")
    @Log(title = "火车车站", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(trainStationService.deleteTrainStationByIds(ids));
    }


    /**
     * 查询火车车站列表（分组）
     */
    @PreAuthorize("@ss.hasPermi('base:train-station:list')")
    @GetMapping("/list")
    public TableDataInfo groupList(TrainStation trainStation) {
        // 确保分页参数有效，避免空指针异常
        if (trainStation.getPageNum() == null) {
            trainStation.setPageNum(1);  // 设置默认页码为1
        }
        if (trainStation.getPageSize() == null) {
            trainStation.setPageSize(10); // 设置默认每页数量为10
        }
        
        startPage();
        Map<String, Object> pageData = trainStationService.selectTrainStationGroups(trainStation);

        // 构造TableDataInfo返回
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows((List<?>) pageData.get("groups")); // 分组后的数据
        rspData.setTotal((Integer) pageData.get("total")); // 总车次数
        return rspData;
    }

    /**
     * 根据车次编号查询车站信息
     */
    @PreAuthorize("@ss.hasPermi('base:train-station:list')")
    @GetMapping("/listByTrainId/{trainId}")
    public TableDataInfo listByTrainId(@PathVariable("trainId") Long trainId, TrainStation trainStation)
    {
        // 确保分页参数有效，避免空指针异常
        if (trainStation.getPageNum() == null) {
            trainStation.setPageNum(1);  // 设置默认页码为1
        }
        if (trainStation.getPageSize() == null) {
            trainStation.setPageSize(10); // 设置默认每页数量为10
        }
        
        // 使用BaseController的startPage方法处理分页
        startPage();  // 这会使用trainStation中的分页参数
        
        // 获取Train对象以获取trainCode
        Train train = trainService.selectTrainById(trainId);
        if (train != null) {
            // 设置查询条件为trainCode而非trainId
            trainStation.setTrainCode(train.getCode());
        }
        
        // 执行查询
        List<TrainStation> list = trainStationService.selectTrainStationList(trainStation);
        return getDataTable(list);
    }

    /**
     * 获取指定列车的所有站点（不分页）
     */
    @PreAuthorize("@ss.hasPermi('base:train-station:list')")
    @GetMapping("/listAllByTrainCode/{trainCode}")
    public AjaxResult listAllByTrainCode(@PathVariable("trainCode") String trainCode) {
        TrainStation trainStation = new TrainStation();
        trainStation.setTrainCode(trainCode);
        List<TrainStation> list = trainStationService.selectTrainStationList(trainStation);
        return AjaxResult.success(list);
    }

    /**
     * 导出导入错误数据
     */
    @PreAuthorize("@ss.hasPermi('base:train-station:export')")
    @Log(title = "火车车站", businessType = BusinessType.EXPORT)
    @PostMapping("/exportErrorData")
    public void exportErrorData(HttpServletResponse response, @RequestParam(required = false) String errorData) throws IOException {
        List<TrainStationVo> errorDataList = new ArrayList<>();
        
        if (StringUtils.hasText(errorData)) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                List<Map<String, Object>> dataList = mapper.readValue(errorData, new TypeReference<List<Map<String, Object>>>() {});
                
                for (Map<String, Object> item : dataList) {
                    TrainStationVo vo = new TrainStationVo();
                    
                    // 设置基本字段
                    vo.setTrainCode(item.get("trainCode") != null ? item.get("trainCode").toString() : "");
                    vo.setName(item.get("name") != null ? item.get("name").toString() : "");
                    vo.setNamePinyin(item.get("namePinyin") != null ? item.get("namePinyin").toString() : "");
                    vo.setInTime(item.get("inTime") != null ? item.get("inTime").toString() : "");
                    vo.setOutTime(item.get("outTime") != null ? item.get("outTime").toString() : "");
                    vo.setStopTime(item.get("stopTime") != null ? item.get("stopTime").toString() : "");
                    vo.setKm(item.get("km") != null ? item.get("km").toString() : "");
                    vo.setErrorMsg(item.get("errorMsg") != null ? item.get("errorMsg").toString() : "");
                    
                    // 处理ID字段
                    if (item.get("id") != null) {
                        try {
                            vo.setId(Long.parseLong(item.get("id").toString()));
                        } catch (Exception e) {
                            vo.setId(IdUtil.getSnowflakeNextId());
                            logger.warn("解析ID失败，已生成新ID: " + e.getMessage());
                        }
                    } else {
                        vo.setId(IdUtil.getSnowflakeNextId());
                    }
                    
                    // 处理站序字段
                    if (item.get("index") != null) {
                        try {
                            vo.setIndex(Long.parseLong(item.get("index").toString()));
                        } catch (Exception e) {
                            vo.setIndex(0L);
                            logger.warn("解析站序失败: " + e.getMessage());
                        }
                    } else {
                        vo.setIndex(0L);
                    }
                    
                    // 处理行号字段
                    if (item.get("rowNum") != null) {
                        try {
                            vo.setRowNum(Integer.parseInt(item.get("rowNum").toString()));
                        } catch (Exception e) {
                            vo.setRowNum(0);
                            logger.warn("解析行号失败: " + e.getMessage());
                        }
                    } else {
                        vo.setRowNum(0);
                    }
                    
                    errorDataList.add(vo);
                }
            } catch (Exception e) {
                logger.error("解析错误数据失败", e);
            }
        }
        
        try {
            trainStationService.exportCustomErrorData(response, errorDataList);
        } catch (Exception e) {
            logger.error("导出错误数据失败", e);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write("{\"code\":500,\"msg\":\"导出错误数据失败\"}");
        }
    }

    /**
     * 清空火车站点数据
     */
    @PreAuthorize("@ss.hasPermi('base:train-station:remove')")
    @Log(title = "火车车站", businessType = BusinessType.CLEAN)
    @PostMapping("/clear")
    public AjaxResult clear(@RequestBody Map<String, String> passwordMap) {
        String password = passwordMap.get("password");
        System.out.println("密码：" + password);
        // 验证当前用户密码
        if (!SecurityUtils.matchesPassword(password, SecurityUtils.getLoginUser().getPassword())) {
            return AjaxResult.error("密码验证失败");
        }
        return toAjax(trainStationService.clearTrainStation());
    }
}
